//
//  YHNetworkTools.swift
//  Swift网络框架封装
//
//  Created by 昱含 on 16/5/22.
//  Copyright © 2016年 YuHan. All rights reserved.
//

import UIKit
import AFNetworking

enum HTTPMethods: Int {
    
    case POST
    case GET
}

struct API {
    
    static let hoseName = "https://api.weibo.com/"
    
    static let loadUserInfo = "2/users/show.json"
    
    static let loadAccessToken = "oauth2/access_token"
    
    static let loadHomeData = "2/statuses/home_timeline.json"
    //发布微博
    static let sendStatus = "2/statuses/update.json"
    //发布图片微博
    static let sendImageStatus = "https://upload.api.weibo.com/2/statuses/upload.json"
}
class YHNetworkTools: AFHTTPSessionManager {
    
    static let sharedTools: YHNetworkTools = {
        
        let url = NSURL(string: API.hoseName)
        
        let tools = YHNetworkTools(baseURL: url)
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
    func request(method: HTTPMethods,urlString: String, parameters: AnyObject?, finished:(responseObject: AnyObject?, error: NSError?) -> ()){
        
        let success = {(task: NSURLSessionDataTask,result: AnyObject?) -> () in
            finished(responseObject: result, error: nil)
        }
        
        let failure = {(task: NSURLSessionDataTask?, error: NSError) -> () in
            finished(responseObject: nil, error: error)
            print(error)
            
        }
        
        if method == .GET {
            
            GET(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }else{
            
            POST(urlString, parameters: parameters, progress: nil, success: success, failure: failure)
            
        }
    }

}


extension YHNetworkTools{
    
    func loadAccessToken(code: String, finished: (responseObject: AnyObject?, error: NSError?)->()) {
        
//        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        let parameters = ["client_id" : client_id, "client_secret":client_secret, "grant_type": "authorization_code","code":code,"redirect_uri":redirect_uri]
        
        request(.POST, urlString: API.loadAccessToken, parameters: parameters, finished: finished)
        
    }
    
    func loadUserInfo(result:[String : AnyObject],finished: (responseObject: AnyObject?, error: NSError?)->()){
        
        let token = result["access_token"]!
        let uid = result["uid"]!
//        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameters = ["access_token": token, "uid": uid]
        request(.GET, urlString: API.loadUserInfo, parameters: parameters, finished: finished)

    }
    
    func loadHomePageData(since_id: Int64, max_id: Int64, finished: (responseObject: AnyObject?, error: NSError?)->()) {
        
        guard let token = YHUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else{
            return
        }
        var parameters = ["access_token": token]
        if since_id > 0 {
            parameters["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            
            parameters["max_id"] = "\(max_id)"
        }
        request(.GET, urlString: API.loadHomeData, parameters: parameters, finished: finished)
    }
}

extension YHNetworkTools {
    func sendStatus(status: String,images: [UIImage], finished: (responseObject: AnyObject?, error: NSError?) -> ()) {
        guard let token = YHUserAccountViewModel.sharedAccountViewModel.userAccount?.access_token else {
            return
        }
        
        let parameters = ["access_token": token,"status":status]
        if images.count > 0 {
           
            self.POST(API.sendImageStatus, parameters: parameters, constructingBodyWithBlock: { (formdata) in
                for image in images{
                     let imageData = UIImagePNGRepresentation(image)!
                    formdata.appendPartWithFileData(imageData, name: "pic", fileName: "any", mimeType: "application/octet-stream")
                }
                //二进制数据不能放到参数中
                
                }, progress: nil, success: { (_, result) in
                    finished(responseObject: result, error: nil)
                }, failure: { (_, error) in
                    finished(responseObject: nil, error: error)
            })
        }else{
            
            request(.POST, urlString: API.sendStatus, parameters: parameters, finished: finished)
        }
    }
}
